import { defineStore } from 'pinia'

const useGoodsStore = defineStore('goods', {
  state: () => {
    return {
      // 定义状态
      cartList: [],
      selectCartList: [],
    }
  },
  actions: {
    // 定义 actions，可以包含异步操作
    initCartList(list) {
      this.cartList = list
      list?.forEach((item) => {
        this.selectCartList.push(item.goodsId)
      })
    },
    checkedAll() {
      this.selectCartList = this.cartList.map((item) => {
        item.checked = true
        return item.goodsId
      })
    },
    unCheckedAll() {
      this.cartList.map((item) => {
        item.checked = false
      })
      this.selectCartList = []
    },
    checkItem(goodsId) {
      const goodsInfo = this.cartList.find((item) => item.goodsId === goodsId)
      if (!goodsInfo?.goodsId) return

      //当前是选中状态--取消操作
      if (goodsInfo.checked) {
        goodsInfo.checked = false
        this.selectCartList.splice(this.selectCartList.indexOf(goodsId), 1)
      } else {
        //当前是未选中状态 -- 选中操作
        goodsInfo.checked = true
        this.selectCartList.push(goodsId)
        //去重
        this.selectCartList = [...new Set(this.selectCartList)]
      }
    },
    checkAllFn(status) {
      status ? this.checkedAll() : this.unCheckedAll()
    },
    stepChange(goodsId, goodsNum) {
      this.cartList.forEach((item, index) => {
        if (item.goodsId === goodsId) {
          this.cartList[index].goodsNum = goodsNum
        }
      })
    },
  },
  getters: {
    // 定义 getters，类似于计算属性
    isCheckedAll: (state) => {
      if (!state.cartList?.length || !state.selectCartList?.length) return false
      return state.cartList?.length === state.selectCartList?.length
    },
    getTotal(state) {
      // console.log('getTotal :>> todo')
      let total = { num: 0, price: 0 }
      state.cartList?.forEach((v) => {
        if (v?.checked) {
          total.num += parseInt(v.goodsNum)
          total.price += v.goodsNum * v.goodsPrice
        }
      })
      return total
    },
  },
})

export default useGoodsStore
